package com.sqlcheck.dto.response;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Data
@Schema(description = "数据库连接测试响应")
public class TestDatabaseConnectionResponse {

    @Schema(description = "连接是否成功", example = "true")
    private boolean success;

    @Schema(description = "响应消息", example = "连接成功")
    private String message;

    @Schema(description = "数据库版本信息", example = "MySQL 8.0.33")
    private String databaseVersion;

    @Schema(description = "标准化的版本号", example = "8.0.33")
    private String normalizedVersion;

    @Schema(description = "连接耗时（毫秒）", example = "150")
    private Long connectionTime;

    public static TestDatabaseConnectionResponse success(String message, String databaseVersion, Long connectionTime) {
        TestDatabaseConnectionResponse response = new TestDatabaseConnectionResponse();
        response.setSuccess(true);
        response.setMessage(message);
        response.setDatabaseVersion(databaseVersion);
        response.setNormalizedVersion(extractNormalizedVersion(databaseVersion));
        response.setConnectionTime(connectionTime);
        return response;
    }

    public static TestDatabaseConnectionResponse failure(String message) {
        TestDatabaseConnectionResponse response = new TestDatabaseConnectionResponse();
        response.setSuccess(false);
        response.setMessage(message);
        return response;
    }
    
    /**
     * 从完整版本信息中提取标准化版本号
     */
    private static String extractNormalizedVersion(String databaseVersion) {
        if (databaseVersion == null) {
            return null;
        }
        
        try {
            // MySQL 8.0.33 -> 8.0.33
            // Oracle 19c (19.3.0.0.0) -> 19.3.0.0.0
            if (databaseVersion.contains("MySQL ")) {
                return databaseVersion.substring(databaseVersion.indexOf("MySQL ") + 6).trim();
            } else if (databaseVersion.contains("Oracle ") && databaseVersion.contains("(")) {
                int start = databaseVersion.indexOf("(") + 1;
                int end = databaseVersion.indexOf(")", start);
                if (end > start) {
                    return databaseVersion.substring(start, end).trim();
                }
            }
            
            // 回退：尝试提取数字和点的版本模式
            String[] parts = databaseVersion.split("\\s+");
            for (String part : parts) {
                if (part.matches("\\d+(\\.\\d+)*")) {
                    return part;
                }
            }
            
            return databaseVersion;
        } catch (Exception e) {
            return databaseVersion;
        }
    }
}